package au.com.bluelink.scjp.chap6;

import java.io.*;

public class SerializableTest {
	public static void main(String[] args) {

		System.out.println("testing SerializeCat...");
		SerializeCat.test();
		
		System.out.println("testing SuperNotSerial...");
		SuperNotSerial.test();

		/*
		  	If you serialize a collection or an array, every element must be
			serializable! A single non-serializable element will cause serialization to fail. Note also
			that while the collection interfaces are not serializable, the concrete collection classes in
			the Java API are. 
		 */ 
		
	}
}

@SuppressWarnings("serial")
class Cat implements Serializable {

} // 1

class SerializeCat {
	public static void test() {
		Cat c = new Cat(); // 2
		try {
			FileOutputStream fs = new FileOutputStream("testSer.ser");
			ObjectOutputStream os = new ObjectOutputStream(fs);
			os.writeObject(c); // 3
			os.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

		try {
			FileInputStream fis = new FileInputStream("testSer.ser");
			ObjectInputStream ois = new ObjectInputStream(fis);
			c = (Cat) ois.readObject(); // 4
			ois.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

class SuperNotSerial {
	public static void test() {
		Dog d = new Dog(35, "Fido");
		System.out.println("before: " + d.name + " " + d.weight);
		try {
			FileOutputStream fs = new FileOutputStream("testSer.ser");
			ObjectOutputStream os = new ObjectOutputStream(fs);
			os.writeObject(d);
			os.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		try {
			FileInputStream fis = new FileInputStream("testSer.ser");
			ObjectInputStream ois = new ObjectInputStream(fis);
			d = (Dog) ois.readObject();
			ois.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println("after: " + d.name + " " + d.weight);
	}
}

@SuppressWarnings("serial")
class Dog extends Animal implements Serializable {
	String name;

	Dog(int w, String n) {
		weight = w; // inherited
		name = n; // not inherited
	}
}

class Animal { // not serializable !
	int weight = 42;
}